Testing with mocks only proves you know how to write mocks.
Dan Allen
Next
Introduction
Next
Challenges of Persistence Tests
Most violated rules in persistence tests
PhoneTest.java@Inject
PhoneService phoneService;
@Test
public void should_insert_phone() {
phoneService.save(new Phone());
}
@Test
public void should_count_phones() {
int numberOfPhones = phoneService.count(); (1)
assertThat(numberOfPhones, equalTo(??));
}| 1 | Depending on execution order the count query returns different number |
Next
Solutions
import static com.lordofthejars.nosqlunit.mongodb.ManagedMongoDb.MongoServerRuleBuilder.newManagedMongoDbRule;
@ClassRule
public static ManagedMongoDb managedMongoDb = newManagedMongoDbRule().mongodPath("/opt/mongo").build(); (1)| 1 | Starts a MongoDB instance installed on /opt/mongo |
@Rule
public MongoDbRule remoteMongoDbRule = new MongoDbRule(mongoDb().databaseName("test").host("host").build());; (1)
@Test
@UsingDataSet(locations="initialData.json", loadStrategy=LoadStrategyEnum.CLEAN_INSERT) (2)
@ShouldMatchDataSet(location="expectedData.json") (3)
public void book_should_be_inserted_into_repository() {| 1 | Establish a connection to given host |
| 2 | Clean the Redis instance and populate with given dataset. |
| 3 | After test expectations are run |
{
"Book":
[
{"title":"The Hobbit","numberOfPages":293},
{"title":"The Lord Of The Rings","numberOfPages":1299}
]
}but my tests run within a container
Next
Origin of the Problem
@Stateless
public class SeriesWithPersistenceContext {
@PersistenceContext
private EntityManager entityManager;
public void createSerie(Serie serie) {
this.entityManager.persist(serie);
}
}@Resource
String host;
@Resource
int port;
@PostConstruct
private void initDB() {
try {
Mongo m = new Mongo(host, port);
DB db = m.getDB("personDB");
//...
} catch (UnknownHostException ex) {
getLogger(PersonSessionBean.class.getName()).log(Level.SEVERE, null, ex);
}
}